<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\AdminController;
use App\Models\Good as TGood;
use Illuminate\Http\Request;
use App\Models\Level;
use App\Models\FeeGood;
use App\Models\Channel;
use App\Models\FeeItem;
use App\Models\GoodOption;
use App\Models\GoodItem;
use App\Models\Cate;

class Good extends AdminController{
    
    public function index(Request $req){
        $type = $req->input("type",0);
        if($req->method() == 'POST'){
            if($req->post('op') == 'status' || $req->post('op') == 'ostatus'){
                if ($req->post('op') == 'ostatus') $g = GoodOption::find($req->post('gid'));
                else if ($type < 10) $g = FeeGood::find($req->post('gid'));
                else $g = TGood::find($req->post('gid'));
                $g->status = $g->status == 1 ? 0 : 1;
                $g->save();
                wxresp(1);
            }
            if ($type < 10) {
                $list = FeeGood::where('type',$type)->orderByRaw('title+0')->get();
                foreach ($list as &$v) {
                    $v->agentprice = json_decode($v->agentprice,1);
                    $v->items = FeeItem::where('gid',$v->id)->select('id','cid','title','costprice','itemno','status')->orderBy('costprice')->get();
                }
            }else{
                $psize = 100;
                $page = $req->post('page',1);
                $cid = $req->post('cid',0);
                $title = $req->post('title','');
                $list = TGood::offset(($page-1)*$psize)->limit($psize);
                if ($cid > 0) $list->where('cid',$cid);
                if ($title) $list->where('title','like',"%{$title}%");
                $list = $list->orderByDesc('id')->get();
                foreach ($list as &$v) {
                    $v->logo = getImage($v->logo);
                    $items = GoodOption::where('gid',$v->id)->orderByRaw('oldprice+0')->get();
                    $arr = [];
                    foreach ($items as $i) {
                        if(!isset($arr[$i['ptitle']])) $arr[$i['ptitle']] = [];
                        $arr[$i['ptitle']][] = $i;
                    }
                    $items = [];
                    foreach ($arr as $t => $as) {
                        $m = array('title'=>$t,'items'=>[]);
                        foreach ($as as $a) {
                            $a['agentprice'] = json_decode($a['agentprice'],1);
                            $a['cnum'] = GoodItem::where('oid',$a['id'])->count();
                            $a['cprice'] = GoodItem::where('oid',$a['id'])->min('costprice');
                            $m['items'][] = $a;
                        }
                        $items[] = $m;
                    }
                    $v->items = $items;
                }
            }
            wxresp(1,['list'=>$list,'levels'=>Level::pluck('title','level'),'channel'=>Channel::pluck('title','id'),'cate'=>Cate::get()]);
        }
        return $this->V("index",array('type'=>$req->get('type',0)));
    }
    
    public function del(Request $req){
        if ($req->method() == 'POST') {
            if ($req->post('op') == 'item') {
                FeeGood::where('id',$req->post('gid'))->delete();
                FeeItem::where('gid',$req->post('gid'))->delete();
                wxresp(1);
            }elseif ($req->post('op') == 'option') {
                $oid = $req->post('oid');
                GoodOption::where('id',$oid)->delete();
                wxresp(1);
            }
            $id = $req->input('gid', 0);
            $item = TGood::find($id);
            if (!$item) wxresp(0, '商品不存在');
            TGood::where('id', $id)->delete();
            GoodOption::where('gid',$id)->delete();
            wxresp(1);
        }
        wxresp(0);
    }
    
    public function post(Request $req){
        $type = $req->input("type",0);
        $gid = $req->input("gid",0);
        if ($type < 10) {
            $data = [
                    'title' => $req->post('title'),
                    'type' => $type,
                    'marketprice' => $req->post('marketprice'),
                    'agentprice' => json_encode($req->post('agentprice')),
                    'status'=>0
            ];
            if (empty($data['title'])) wxresp(0,'面值不能为空');
            if ($gid){
                FeeGood::where('id', $gid)->update($data);
                $data['id'] = $gid;
            }else{
                $data['id'] = FeeGood::insertGetId($data);
            }
            $data['agentprice'] = json_decode($data['agentprice'],1);
        }else{
            if ($req->post('op') == 'item') {
                $data = json_decode($req->post('data'),1);
                if (isset($data['isedit'])) {
                    GoodOption::where('id',$data['items'][0]['id'])->update(array(
                            'title'=>$data['items'][0]['title'],
                            'marketprice'=>$data['items'][0]['marketprice'],
                            'oldprice'=>$data['items'][0]['oldprice'],
                            'agentprice'=>json_encode($data['items'][0]['agentprice']),
                    ));
                    wxresp(1);
                }
                $item = ['title'=>$data['title'],'items'=>[]];
                foreach ($data['items'] as $v) {
                    $v['id'] = GoodOption::insertGetId(array(
                            'gid'=>$gid,
                            'ptitle'=>$data['title'],
                            'title'=>$v['title'],
                            'marketprice'=>$v['marketprice'],
                            'oldprice'=>$v['oldprice'],
                            'agentprice'=>json_encode($v['agentprice']),
                    ));
                    $item['items'][] = $v;
                }
                wxresp(1,['item'=>$item]);
            }
            $data = array(
                    'title'=>$req->post('title'),
                    'logo'=>uploadImage($req->post('logo')),
                    'cid'=>$req->post('cid'),
                    'rule'=>$req->post('rule'),
            );
            if ($gid){
                TGood::where('id', $gid)->update($data);
                $data['id'] = $gid;
            }else{
                $data['id'] = TGood::insertGetId($data);
            }
            $data['logo'] = getImage($data['logo']);
        }
        wxresp(1,array('item'=>$data));
    }
    
    public function bind(Request $req){
        $gid = $req->input("gid",0);
        if ($req->post('op') == 'unitembind') {
            GoodItem::where('id',$gid)->delete();
            wxresp(1);
        }
        if ($req->post('op') == 'unbind') {
            FeeItem::where('id',$gid)->delete();
            wxresp(1);
        }
        if ($req->post('op') == 'cgood') {
            $oid = $req->input("oid",0);
            $list = GoodItem::where('oid',$oid)->orderBy('costprice')->get();
            wxresp(1,['list'=>$list]); 
        }
        
        $cid = $req->input("cid",0);
        $channel = Channel::find($cid);
        $api = explode(",", $channel['apitoken']);
        $channel['appid'] = $api[0];
        $channel['appkey'] = $api[1];
        $itemno = $req->post('itemno');
        $res = Channel::channelPost($channel, 'goods', array('gids'=>[$itemno]));
        if ($res['code'] != 1) wxresp(0,$res['msg']);
        if (empty($res['list'])) wxresp(0,'商品不存在或已下架');
        $ngood = $res['list'][0];
        if ($req->post('op') == 'docgood') {
            $oid = $req->input("oid",0);
            $g = GoodOption::find($oid);
            $item = array(
                    'gid'=>$g->gid,
                    'oid'=>$oid,
                    'title'=>$ngood['title'],
                    'cid'=>$cid,
                    'itemno'=>$itemno,
                    'costprice'=>$ngood['price'],
                    'status'=>0
            );
            $item['id'] = GoodItem::insertGetId($item);
        }else{
            $item = array(
                    'gid'=>$gid,
                    'title'=>$ngood['title'],
                    'cid'=>$cid,
                    'itemno'=>$itemno,
                    'costprice'=>$ngood['price'],
                    'status'=>0
            );
            $item['id'] = FeeItem::insertGetId($item);
        }
        wxresp(1,array('item'=>$item));
    }
    
    public function cate(Request $req){
        if($req->post('op') == 'del'){
            $cid = $req->input("cid",0);
            if (TGood::where('cid',$cid)->count() > 0) wxresp(0,'该分类已绑定商品，请先解绑');
            Cate::where('id',$cid)->delete();
            wxresp(1);
        }
        if($req->post('op') == 'add'){
            $data = $req->post('data');
            if (empty($data)) wxresp(0,'没有修改');
            foreach ($data as $value) {
                if (!isset($value['id'])) $c = new Cate();
                else $c = Cate::find($value['id']);
                $c->title = $value['title'];
                $c->save();
            }
            wxresp(1,['cate'=>Cate::get()]);
        }
    }
}